package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.nio.CharBuffer;

public class ResultFileWriter{

	private String filename = null;
	PrintWriter writer;


	public ResultFileWriter(String filename) {
		this.filename = filename;
	}
	
	public void appendToLeftEnd(String[] msg,String newfilename){
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {

			String line = new String();
			
			reader = new BufferedReader(new FileReader(filename) );
			writer = new BufferedWriter(new FileWriter(newfilename)) ;
			int i=0;
			while((line = reader.readLine())!= null)
			{	//System.out.println(line);
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append(line);
				stringBuilder.append(msg[i]+"\r\n");
				writer.write(stringBuilder.toString());
				i++;
			}
			reader.close();
			writer.close();
			File target = new File(filename);
			target.delete();
			filename = newfilename;

		} catch (FileNotFoundException ex) {
			System.err.println("File Not Found");
		}
		catch (IOException e) {
			System.err.println("Unable to close the file");
		}
	}
	public void logWoReOpen(String msg){
		writer.print(msg);
	}

	public void log(String msg) {

		try {
			PrintWriter out = new PrintWriter( 
					new BufferedWriter(new FileWriter(filename, true)));
			out.print(msg);
			out.close();
		} catch (FileNotFoundException ex) {
			System.err.println("File Not Found");
		}
		catch (IOException e) {
			System.err.println("Unable to close the file");
		}


	}
	public boolean open(){
		try{
		writer = new PrintWriter( 
				new BufferedWriter(new FileWriter(filename, true)));
		}
		catch (IOException e) {
			System.err.println("Unable to open the file");
			return false;
		}
		return true;
	}
	public boolean close(){
		writer.close();
		return true;
	}
	
	public String getText(){
		BufferedReader reader = null;
		String chars = null;
		try {
			reader = new BufferedReader(new FileReader(filename) );
		
			chars = reader.readLine();
		} catch (IOException e) {
			return null;
		}
		if(chars == null)
			return null;
		else
			return chars.toString();
	}

	public void setText(String text){
		PrintWriter out = null ;
		try {
			out = new PrintWriter( new BufferedWriter(new FileWriter(filename,false)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.print(text);
		out.close();
	}

}
